// 直接定义API配置，避免导入问题
const apiConfig = {
  // 临时使用本地后端测试
  baseURL: 'http://127.0.0.1:8081',
  timeout: 10000
}

// 请求拦截器
const requestInterceptor = (options) => {
  // 添加token到请求头
  const token = uni.getStorageSync('token')
  if (token) {
    options.header = options.header || {}
    options.header['Authorization'] = `Bearer ${token}`
  }
  
  // 设置默认请求头
  options.header = {
    'Content-Type': 'application/json',
    ...options.header
  }
  
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  // HTTP状态码检查
  if (statusCode === 200) {
    // 业务状态码检查
    if (data.code === 200) {
      return data
    } else if (data.code === 401) {
      // token过期，清除本地存储并跳转到登录页
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.reLaunch({
        url: '/pages/login/login'
      })
      return Promise.reject(new Error(data.msg || '登录已过期'))
    } else {
      return Promise.reject(new Error(data.msg || '请求失败'))
    }
  } else if (statusCode === 401) {
    // 未授权
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    uni.reLaunch({
      url: '/pages/login/login'
    })
    return Promise.reject(new Error('登录已过期'))
  } else {
    return Promise.reject(new Error(`请求失败: ${statusCode}`))
  }
}

// 请求方法
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 检查API配置
    if (!apiConfig || !apiConfig.baseURL) {
      reject(new Error('API配置错误'))
      return
    }
    
    // 确保baseURL以http开头
    if (!apiConfig.baseURL.startsWith('http')) {
      reject(new Error('baseURL格式错误'))
      return
    }
    
    // 处理请求拦截器
    const fullUrl = `${apiConfig.baseURL}${options.url}`
    console.log('完整请求URL:', fullUrl)
    
    // 注意：不能让 ...options 覆盖我们拼接的 fullUrl
    const processedOptions = requestInterceptor({
      ...options,
      url: fullUrl,
      method: options.method || 'GET',
      data: options.data,
      header: options.header,
      timeout: options.timeout || apiConfig.timeout
    })
    
    uni.request({
      ...processedOptions,
      success: (response) => {
        try {
          const result = responseInterceptor(response)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      },
      fail: (error) => {
        console.error('请求失败:', error)
        reject(new Error('网络请求失败'))
      }
    })
  })
}

// 便捷方法
export const get = (url, params = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
    ...options
  })
}

export const post = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

export const put = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

export const del = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}

export default request
